package managedbean.CRM.ProductPrice;

import entity.CRM.ProductPrice;
import javaclass.ProductType;
import java.io.Serializable;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.PhaseEvent;
import session.stateless.CRM.ProductPriceBeanLocal;

@ManagedBean
@ViewScoped
public class EditProductPriceManagerBean implements Serializable
{
    @EJB
    private ProductPriceBeanLocal productBeanLocal;
    private ProductPrice productToEdit;
    private ProductType productType;
    private String statusMessage;

    public ProductPrice getProductToEdit() {
        return productToEdit;
    }
    public void setProductToEdit(ProductPrice productToEdit) {
        this.productToEdit = productToEdit;
    }

    public String getStatusMessage() {
        return statusMessage;
    }

    public void setStatusMessage(String statusMessage) {
        this.statusMessage = statusMessage;
    }

    public EditProductPriceManagerBean() {}
    
    public void initView(PhaseEvent event){
        if(productToEdit == null)
        {            
            productToEdit = (ProductPrice)FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("selectedProductPrice"); 
            productType = productToEdit.getProductType(); 
        }
    }
    
    public void updateProductPrice(ActionEvent event){
        try
        {
            if (productBeanLocal.checkConflict(productToEdit.getProductPriceId(), productType, productToEdit.getLowerLimit(), productToEdit.getHigherLimit()))
            {
                statusMessage = "Overlapping range limit. Please try again.";
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Unsuccessful:" + statusMessage + "", ""));
            }
            else
            {
            productBeanLocal.updateProductPrice(productToEdit.getProductPriceId(), productType, productToEdit.getLowerLimit(), productToEdit.getHigherLimit(), productToEdit.getProductPrice());
            System.out.println("ProductPriceType after edit:"+ productToEdit.getProductType());

            statusMessage = "ProductPrice Updated Successfully."; 

            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,  "Update ProductPrice Result: " + statusMessage, "")); 
            }
        }
        catch (Exception ex) 
        {
            ex.printStackTrace();
        }
    }    
}

